
import { Card, Input, Form, Button, Tooltip, Table, Popover, Popconfirm, Modal, message, Checkbox, Divider } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, UserOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react'
import { reqGetUserList, reqAddUser, reqDeleteById, reqEditUser, reqGetRoles, reqSaveRoles } from '@/api/acl/acluser';
import type { userListType } from '@/api/acl/model/acluserType'
interface DataType {
  index: number;
  username: string;
  nickName: string;
  roleName: string;
  gmtCreate: number;
  gmtModified: number;
}
let plainOptions: any = [];
export default function User() {
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      width: 80,
      dataIndex: 'index',
      render: (a, b, index) => {
        return index + 1
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
    },
    {
      title: '角色列表',
      dataIndex: 'roleName',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
    },
    {
      title: '操作',
      width: 250,
      dataIndex: 'control',
      render: (a, row: userListType, index) => {
        // console.log(row);
        // console.log(a);               
        return (
          <>
            <Popover content="分配角色" trigger="hover">
              <Button shape="round" type="primary" icon={<UserOutlined />} onClick={() => giveRole(row)} />
            </Popover>
            <Popover content="修改用户" trigger="hover">
              <Button shape="round" type="primary" icon={<EditOutlined />} style={{ marginLeft: 10 }} onClick={() => editUser(row)} />
            </Popover>
            <Popover content="删除用户" trigger="hover">
              <Popconfirm title="确定要删除吗" okText="确定" cancelText="取消" onConfirm={deleteUser}>
                <Button shape="round" type="primary" icon={<DeleteOutlined />} style={{ marginLeft: 10 }} onClick={() => remove(row)} />
              </Popconfirm>
            </Popover>
          </>
        )
      }
    },
  ];
  const [id, setId] = useState<any>()

  const [userList, setUserList] = useState<any>([]);

  const [loading, setLoading] = useState(false);

  const [total, setTotal] = useState(0)
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5);


  const CheckboxGroup = Checkbox.Group;

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isRoleModal, setIsRoleModal] = useState(false)

  const [all, setAll] = useState([])

  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  // 获取用户列表
  const getUserList = async (page: number, limit: number) => {
    const username = form.getFieldsValue()
    const result = await reqGetUserList(page, limit, username)
    setUserList(result.items);
    setTotal(result.total)
    setCurrent(page);
    setPageSize(limit);
  }
  useEffect(() => {
    getUserList(current, pageSize)
  }, [])
  // 删除按钮
  const remove = (e: any) => {
    setId(e.id)
  }
  // 删除用户
  const deleteUser = async () => {
    await reqDeleteById(id)
    getUserList(current, pageSize)
    message.success('删除成功')
  }
  // 修改用户
  const editUser = async (row: any) => {
    setIsModalOpen(true);
    setId(row.id)
    form1.setFieldsValue(row)
  }
  // 添加按钮的点击事件
  const addUser = () => {
    form1.resetFields()
    setIsModalOpen(true);
    setId('')
    form.setFieldsValue({ username: undefined, password: undefined, nickName: undefined });
  }
  // 添加对话框的取消按钮
  const handleCancel = () => {
    setIsModalOpen(false);
  }
  // 添加对话框的确定按钮的事件回调   
  const handleOk = async () => {
    console.log(123);
    const { username, password, nickName } = form1.getFieldsValue()
    console.log(id)
    if (id) {
      let result = await reqEditUser({ username, password, nickName, id })
      message.success('修改成功')
      console.log("修改:", result);
    } else {
      let result = await reqAddUser({ username, password, nickName })
      message.success('添加成功')
      console.log("添加：", result);
    }
    // 关闭添加和修改的对话框
    setIsModalOpen(false);

    form1.resetFields()
    // 重新获取数据
    getUserList(current, pageSize)
  }
  // 搜索用户
  const searchUser = () => {
    getUserList(current, pageSize)
  }
  // 清空
  const clearAll = () => {
    form.setFieldsValue({ username: undefined })
    getUserList(current, pageSize)
  }
  // 分配角色
  const giveRole = async (row: any) => {
    console.log('row:', row);     
    setId(row.id)
    form.setFieldsValue({ username: row.username })
    let result = await reqGetRoles(row.id)
    console.log("roles:", result);
    setAll(result.allRolesList)
    plainOptions = result.allRolesList.map((item: any) => {
      return item.roleName
    })
    const assignRoles = result.assignRoles.map((item: any) => {
      return item.roleName
    })
    console.log(plainOptions);
    setIsRoleModal(true)
    setCheckedList(assignRoles)
  }
  // 分配角色对话框的保存按钮
  const handleOkRole = async () => {
    let arr = []
    console.log(all);
    console.log(checkedList);
    for(let i =0;i<all.length;i++){
        for(let a =0;a<checkedList.length;a++){
            if(all[i].roleName == checkedList[a]){
                arr.push(all[i].id)
            }
        }
    }
    let roleId = arr.join()
    let userId = id
    await reqSaveRoles(userId, roleId)
    // await reqSaveRoles()
    form.resetFields()
    getUserList(current, pageSize)
    // 关闭对话框
    setIsRoleModal(false)
  }
  // 分配角色对话框的取消按钮
  const handleCancelRole = () => {
    setIsRoleModal(false)
  }

  const [checkedList, setCheckedList] = useState();
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);
  // 角色选项的按钮
  const onChange = (assignRoles: any) => {
    setCheckedList(assignRoles);
    setIndeterminate(!!assignRoles.length && assignRoles.length < plainOptions.length);
    setCheckAll(assignRoles.length === plainOptions.length);;
  };
  // 全选按钮
  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    setCheckedList(e.target.checked ? plainOptions : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);


  };

  return (
    <Card>
      <Form form={form} layout="inline">
        <Form.Item name="username">
          <Input placeholder="用户名" size="large" style={{ width: 200 }} />
        </Form.Item>
        <Form.Item>
          <Button type="primary" size="large" style={{ marginLeft: 10, background: 'skyblue' }} icon={<SearchOutlined />} shape="round" onClick={searchUser} htmlType="submit">查询</Button>
          <Button size="large" style={{ marginLeft: 10 }} shape="round" onClick={clearAll}>清空</Button>
        </Form.Item>
      </Form>
      <Form>
        <Form.Item>
          <Button size="large" style={{ marginLeft: 10 }} shape="round" onClick={addUser}>添加</Button>
          <Button size="large" style={{ marginLeft: 10 }} danger shape="round">批量删除</Button>
        </Form.Item>
      </Form>

      <Modal title="添加用户" visible={isModalOpen} onOk={handleOk} onCancel={handleCancel} okText="确认"
        cancelText="取消">
        <Form {...layout} form={form1} name="control-hooks" >
          <Form.Item name="username" label="用户名" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="nickName" label="用户昵称">
            <Input />
          </Form.Item>
          {id ? "" : <Form.Item name="password" label="用户密码" rules={[{ required: true }]}>
            <Input />
          </Form.Item>}
        </Form>
      </Modal>

      <Modal title="设置角色" visible={isRoleModal} onOk={handleOkRole} onCancel={handleCancelRole} okText="保存"
        cancelText="取消">
        <Form {...layout} form={form} name="control-hooks">
          <Form.Item label="用户名" name="username">
            <Input disabled />
          </Form.Item>
          <Form.Item label="角色列表">
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
              全选
            </Checkbox>
            <Divider />
            <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />
          </Form.Item>
        </Form>
      </Modal>

      <Table
        rowKey="id"
        rowSelection={rowSelection}
        columns={columns}
        dataSource={userList}
        bordered
        pagination={{
          current,
          pageSize,
          total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `总共 ${total} 条`,
          onChange: getUserList,
          pageSizeOptions: [3, 5, 8, 10]
        }}
      />
    </Card>
  )
}
